<template>
    <!-- 三级分类组件 -->
    <categoryVue :sonce="sonce"></categoryVue>
    <br />

    <div v-show="sonce==0">
        <el-button type="primary" size="default" :icon="Plus" @click="attrArr" readonly="readonly"
            :disabled="!CStores.c3ID">添加属性</el-button>

        <el-table border stripe :data="AttrArr" style="margin:20px 0 0 0">
            <el-table-column label="序号" type="index" width="80px" align="center"></el-table-column>
            <el-table-column label="属性名称" width="200" prop="attrName"> </el-table-column>
            <el-table-column label="属性值名称">
                <template #="{row,$index}">
                    <el-tag class="ml-2" type="success" v-for="(val,index) in row.attrValueList" :key="val.id"
                        style="margin:0 5px">{{val.valueName}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150px" align="center">
                <template #="{row,$index}">
                    <el-button type="primary" size="small" :icon="Edit" @click="amend(row)"></el-button>
                    <el-button type="danger" size="small" :icon="Delete" @click="deleteitem(row)"></el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div v-show="sonce==1">
        <el-card shadow="always" :body-style="{ padding: '20px' }">
            <el-form ref="form" :inline="true">
                <el-form-item label="添加属性">
                    <el-input placeholder="请输入" clearable v-model="attrParams.attrName"></el-input>
                </el-form-item>
            </el-form>
            <el-button type="primary" size="default" :icon="Plus" @click="addAttt" :disabled=" !attrParams.attrName">
                添加属性值
            </el-button>
            <el-button size="default" @click="switchover">取消</el-button>
            <el-table border stripe style="margin:20px 0" :data="attrParams.attrValueList">
                <el-table-column label="序号" type="index" width="80px" align="center"></el-table-column>
                <el-table-column label="属性值">
                    <template #="{row,$index}">
                        <el-input placeholder="请输入" size="small" clearable v-model="row.valueName"
                            @blur="toLook(row,$index)" v-if="row.flag" :ref="(vc)=>inputArr[$index] = vc"></el-input>
                        <div @click="toEdit(row,$index)" v-else>{{row.valueName}}</div>

                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #="{row,$index}">
                        <el-button type="danger" size="default" :icon="Delete"
                            @click="attrParams.attrValueList.splice($index,1)"></el-button>

                    </template>
                </el-table-column>
            </el-table>

            <el-button type="primary" size="default" :disabled="attrParams.attrValueList.length>0 ?false:true"
                @click="save">
                保存</el-button>
            <el-button size="default" @click="switchover">取消</el-button>
        </el-card>
    </div>
</template>
  
<script lang="ts" setup>
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Plus,
    UploadFilled,
} from "@element-plus/icons-vue";
import { ref, onMounted, watch, reactive, nextTick } from 'vue'
import { reqAttrList, reqSaveAttrInfo, deleteAttr } from '@/api/product/attr/attr'
import CStore from '@/stores/attr'
import categoryVue from '@/components/category/category.vue';
import { ElMessage } from "element-plus";
import _ from "lodash";

//仓库的实例
let CStores = CStore()
//定义页面切换的变量
let sonce = ref<number>(0)
//页面0的数据存储
let AttrArr = ref([])
//页面1的 定义数组ref类型数据 用来储存el-input组件的实例
let inputArr = ref([])
//  定义的数据
let attrParams = reactive({
    attrName: "", //新增|修改以后属性名字
    categoryId: "", //代表平台属性归属于手机这个三级分类下的
    categoryLevel: 3, //代表几级分类
    attrValueList: [],

})

//页面挂载的时候把三级下拉的数据初始化
onMounted(() => {
    CStores.c1Data = [];
    CStores.c1ID = "";
    CStores.c2Data = [];
    CStores.c2ID = "";
    CStores.c3Data = [];
    CStores.c3ID = "";
})

//页面0修改的逻辑
const amend = (row) => {
    sonce.value = 1
    Object.assign(attrParams, _.cloneDeep(row))
}

//页面0的删除的逻辑
let deleteitem = async (row) => {
    try {
        await deleteAttr(row.id)
        ElMessage({
            type: 'success',
            message: '操作成功'
        })
        getAttrList()
    } catch (error) {
        ElMessage({
            type: 'failure',
            message: '操作失败'
        })
    }
}

//页面1 input的blur事件 触发
let toLook = (row, $index) => {
    row.flag = false
    //判断input的值不能为空 为空直接清除这一条数据 返回
    if (row.valueName.trim() == '') {
        ElMessage({
            type: 'warning',
            message: "属性值不可以为空"
        })
        attrParams.attrValueList.splice($index, 1)

        return;
    }

    //判断添加过的属性不能重复 
    let repeat = attrParams.attrValueList.find((item) => {
        //先除掉自身 在去匹配是否重复
        if (row != item) {
            return row.valueName === item.valueName
        }
    })
    if (repeat) {
        ElMessage({
            type: 'warning',
            message: `${repeat.valueName}重复了`
        })
        attrParams.attrValueList.splice($index, 1)
    }
}
//
let toEdit = (row, $index) => {
    row.flag = true

    nextTick(() => {

        inputArr.value[$index].focus()
        console.log(inputArr.value)
    })
}

//页面1 点击添加属性值触发
let addAttt = () => {
    attrParams.attrValueList.push({
        flag: true,
        valueName: ""
    })
    //获取更新后的最新DOM 并且聚焦
    nextTick(() => {
        inputArr.value[attrParams.attrValueList.length - 1].focus()
    })
}

//点击取消按钮的触发
let switchover = () => {
    sonce.value = 0
}

//页面0 点击添加触发
let attrArr = () => {
    sonce.value = 1
    attrParams.id = ''
    //点击添加时把页面1中的数据全部清空 并且把三级分类的ID直接赋予
    Object.assign(attrParams, {
        attrName: "", //新增|修改以后属性名字
        categoryId: CStores.c3ID, //代表平台属性归属于手机这个三级分类下的
        categoryLevel: 3, //代表几级分类
        attrValueList: [],
    })
}
//监听3ID的变化触发
watch(
    () => CStores.c3ID,
    () => {
        if (CStores.c3ID == '') return
        getAttrList()
    })
//页面0 获取属性列表的数据
let getAttrList = async () => {
    let result = await reqAttrList(CStores.c1ID, CStores.c2ID, CStores.c3ID)
    AttrArr.value = result

}

//页面1保存触发的逻辑
let save = async () => {
    attrParams.attrValueList.forEach((item) => {
        if (item.hasOwnProperty('flag')) {
            delete item.flag
        }
    })
    try {
        await reqSaveAttrInfo(attrParams)
        sonce.value = 0
        ElMessage({
            type: "success",
            message: attrParams.id ? "修改成功" : "添加成功",
        });
        getAttrList()
    } catch (error) {
        ElMessage({
            type: 'success',
            message: attrParams.id ? "修改失败" : "添加失败"
        })
    }
}
</script>

<style scoped>

</style>